#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;
const int N = 4e4 + 10, M = N * 2;

int n, m;
int fa[N][16], depth[N], q[N];
int h[N], e[M], ne[M], idx;



void add(int a, int b){
    e[idx] = b;
    ne[idx] = h[a];
    h[a] = idx ++;
}

void bfs(int root){
    memset(depth, 0x3f, sizeof depth);
    depth[0] = 0;
    int hh = 0, tt = 0;
    q[tt++] = root;
    depth[root] = 1;

    while(hh != tt){
        int t = q[hh++];
        if(hh == N) hh = 0;

        for(int i = h[t]; ~i; i = ne[i]){
            int j = e[i];
            if(depth[j] > depth[t] + 1){
                depth[j] = depth[t] + 1;
                fa[j][0] = t;
                for(int k = 1; k <= 15; k ++){
                    fa[j][k] = fa[fa[j][k - 1]][k - 1];
                }
                q[tt++] = j;
                if(tt == N) tt = 0;
            }
        }
    }
}


int lca(int a, int b){
    if(depth[a] < depth[b]) swap(a, b);

    for(int k = 15; k >= 0; k --){
        if(depth[fa[a][k]] >= depth[b]){
            a = fa[a][k];
        }
    }

    if(a == b) return b;

    for(int k = 15; k >= 0; k--){
        if(fa[a][k] != fa[b][k]){
            a = fa[a][k];
            b = fa[b][k];
        }
    }

    return fa[a][0];
}

int main(){
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    memset(h, -1, sizeof h);

    int root = 0;
    
    scanf("%d", &n);
    for(int i = 0; i < n; i ++){
        int a, b;
        scanf("%d%d", &a, &b);
        if(b == -1) root = a;
        else add(a, b), add(b, a);
    }

    bfs(root);

    scanf("%d", &m);
    while(m --){
        int a, b;
        scanf("%d%d", &a, &b);

        int t = lca(a, b);
        if(t == a) puts("1");
        else if(t == b) puts("2");
        else puts("0");
    }

    return 0;

}